package service

import (
	"context"
	"fmt"
	"order_srv/basic/orderproto"
	"time"
)

// TransitionOrderState 转换订单状态
func (s *Server) TransitionOrderState(ctx context.Context, req *__.TransitionOrderStateReq) (*__.TransitionOrderStateResp, error) {
	// 验证请求参数
	if req.OrderId == 0 {
		return &__.TransitionOrderStateResp{
			Code:    400,
			Message: "订单ID不能为空",
		}, nil
	}
	if req.Event == "" {
		return &__.TransitionOrderStateResp{
			Code:    400,
			Message: "事件不能为空",
		}, nil
	}
	if req.OperatorId == "" {
		return &__.TransitionOrderStateResp{
			Code:    400,
			Message: "操作员ID不能为空",
		}, nil
	}

	// 构建转换请求
	transitionReq := &TransitionRequest{
		OrderID:      req.OrderId,
		Event:        OrderEvent(req.Event),
		OperatorID:   req.OperatorId,
		OperatorType: req.OperatorType,
		Reason:       req.Reason,
		ExtraData:    make(map[string]interface{}),
	}

	// 执行状态转换
	result, err := ExecuteTransition(ctx, transitionReq)
	if err != nil {
		return &__.TransitionOrderStateResp{
			Code:    500,
			Message: fmt.Sprintf("状态转换失败: %v", err),
		}, nil
	}

	if !result.Success {
		return &__.TransitionOrderStateResp{
			Code:    400,
			Message: result.Message,
		}, nil
	}

	// 返回成功结果
	return &__.TransitionOrderStateResp{
		Code:      200,
		Message:   result.Message,
		FromState: int32(result.FromState),
		ToState:   int32(result.ToState),
		Event:     string(result.Event),
		Timestamp: result.Timestamp.Format(time.RFC3339),
	}, nil
}

// GetOrderStateInfo 获取订单状态信息
func (s *Server) GetOrderStateInfo(ctx context.Context, req *__.GetOrderStateInfoReq) (*__.GetOrderStateInfoResp, error) {
	// 验证请求参数
	if req.OrderId == 0 {
		return &__.GetOrderStateInfoResp{
			Code:    400,
			Message: "订单ID不能为空",
		}, nil
	}

	// 获取订单当前状态
	// 这里需要从数据库获取订单信息
	// 暂时返回模拟数据
	currentState := StatePending // 假设当前状态

	// 获取可执行的事件
	validEvents := GetValidEvents(currentState)

	var eventNames []string
	for _, event := range validEvents {
		eventNames = append(eventNames, GetEventName(event))
	}

	return &__.GetOrderStateInfoResp{
		Code:         200,
		Message:      "获取状态信息成功",
		CurrentState: int32(currentState),
		StateName:    GetStateName(currentState),
		ValidEvents:  eventNames,
	}, nil
}

// GetStateMachineDiagram 获取状态机流程图
func (s *Server) GetStateMachineDiagram(ctx context.Context, req *__.GetStateMachineDiagramReq) (*__.GetStateMachineDiagramResp, error) {
	diagram := GetStateMachineDiagram()

	return &__.GetStateMachineDiagramResp{
		Code:    200,
		Message: "获取状态机流程图成功",
		Diagram: fmt.Sprintf("%+v", diagram),
	}, nil
}

// ValidateTransition 验证状态转换
func (s *Server) ValidateTransition(ctx context.Context, req *__.ValidateTransitionReq) (*__.ValidateTransitionResp, error) {
	// 验证请求参数
	if req.OrderId == 0 {
		return &__.ValidateTransitionResp{
			Code:    400,
			Message: "订单ID不能为空",
		}, nil
	}
	if req.Event == "" {
		return &__.ValidateTransitionResp{
			Code:    400,
			Message: "事件不能为空",
		}, nil
	}

	// 获取订单当前状态
	// 这里需要从数据库获取订单信息
	// 暂时使用模拟数据
	currentState := StatePending

	// 验证转换
	canTransition := CanTransition(currentState, OrderEvent(req.Event))

	if canTransition {
		nextState, _ := GetNextState(currentState, OrderEvent(req.Event))
		return &__.ValidateTransitionResp{
			Code:          200,
			Message:       "状态转换有效",
			CanTransition: true,
			FromState:     int32(currentState),
			ToState:       int32(nextState),
			FromStateName: GetStateName(currentState),
			ToStateName:   GetStateName(nextState),
		}, nil
	} else {
		return &__.ValidateTransitionResp{
			Code:          400,
			Message:       "状态转换无效",
			CanTransition: false,
			FromState:     int32(currentState),
			ToState:       int32(currentState),
			FromStateName: GetStateName(currentState),
			ToStateName:   GetStateName(currentState),
		}, nil
	}
}

// GetStateHistory 获取状态历史
func (s *Server) GetStateHistory(ctx context.Context, req *__.GetStateHistoryReq) (*__.GetStateHistoryResp, error) {
	// 验证请求参数
	if req.OrderId == 0 {
		return &__.GetStateHistoryResp{
			Code:    400,
			Message: "订单ID不能为空",
		}, nil
	}

	// 这里应该从数据库获取状态变更历史
	// 暂时返回模拟数据
	history := []*__.StateHistoryItem{
		{
			State:      int32(StatePending),
			StateName:  GetStateName(StatePending),
			Event:      "create",
			EventName:  "创建",
			OperatorId: "system",
			Reason:     "订单创建",
			Timestamp:  time.Now().Add(-2 * time.Hour).Format(time.RFC3339),
		},
	}

	return &__.GetStateHistoryResp{
		Code:    200,
		Message: "获取状态历史成功",
		History: history,
	}, nil
}
